package com.atguigu.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Flink03_Stream_Unbounded_WordCount {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //并行度设置为1
        env.setParallelism(1);

        //2.从无界流读取数据（从端口读数据）
        DataStreamSource<String> streamSource = env.socketTextStream("hadoop102", 9999);

        //3.先按照空格切出每一个单词
        SingleOutputStreamOperator<String> wordStream = streamSource.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    out.collect(word);
                }
            }
        });

        //4.将每一个单词转位Tuple2元组
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordToOneSteam = wordStream.map (value -> Tuple2.of(value, 1))
                //当使用lambda表达式的时候可能会因为泛型擦除报错，可以用以下方法解决
                .returns(Types.TUPLE(Types.STRING,Types.INT));

        //5.将相同单词聚合到一块
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = wordToOneSteam.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            /**
             * 从数据中提取key 也可以不用非得从数据中提取 具体将什么指定为key要看需求
             * @param value
             * @return
             * @throws Exception
             */
            @Override
            public String getKey(Tuple2<String, Integer> value) throws Exception {
                return value.f0;
            }
        });

        //6.累加计算
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = keyedStream.sum(1);

        //打印到控制台
        result.print();

        //执行程序
        env.execute();
    }
}
